<template>
  <div class="personal-info-form-page">
    <!-- 页面头部 -->
    <div class="page-header">
      <button class="back-btn" @click="goBack">
        <span class="back-icon">←</span>
      </button>
      <h2 class="page-title">新增观众信息</h2>
      <div class="header-spacer"></div>
    </div>
    
    <!-- 页面内容 -->
    <div class="page-content">
      <div class="form-container">


        <el-form 
          :model="personalInfo" 
          :rules="formRules"
          ref="formRef"
          label-width="100px" 
          class="personal-info-form"
        >
          <el-form-item label="姓名" prop="name" required>
            <el-input 
              v-model="personalInfo.name" 
              placeholder="请输入真实姓名" 
              maxlength="20"
              show-word-limit
            />
          </el-form-item>
          
          <el-form-item label="联系电话" prop="phone" required>
            <el-input 
              v-model="personalInfo.phone" 
              placeholder="请输入联系电话" 
              maxlength="11"
              @input="handlePhoneInput"
              @blur="handlePhoneBlur"
            />
            <div v-if="phoneCheckStatus === 'exists'" class="phone-error">
              该手机号已被使用，每个手机号只能预约一次
            </div>
          </el-form-item>
          
          <el-form-item label="性别" prop="gender" required>
            <el-radio-group v-model="personalInfo.gender" class="gender-group">
              <el-radio value="男" class="gender-radio">男</el-radio>
              <el-radio value="女" class="gender-radio">女</el-radio>
            </el-radio-group>
          </el-form-item>
          
          <el-form-item label="年龄" prop="age" required>
            <el-input 
              v-model.number="personalInfo.age" 
              placeholder="请输入年龄"
              type="number"
              :min="1"
              :max="120"
              class="age-input"
              @input="handleAgeInput"
            />
          </el-form-item>
          
          <el-form-item label="教育程度" prop="education" required>
            <el-select v-model="personalInfo.education" placeholder="请选择教育程度" class="education-select">
              <el-option label="小学" value="小学" />
              <el-option label="初中" value="初中" />
              <el-option label="高中/中专" value="高中/中专" />
              <el-option label="大专" value="大专" />
              <el-option label="本科" value="本科" />
              <el-option label="硕士" value="硕士" />
              <el-option label="博士" value="博士" />
              <el-option label="其他" value="其他" />
            </el-select>
          </el-form-item>
          
          <el-form-item label="职业/专业" prop="occupation" required>
            <el-input 
              v-model="personalInfo.occupation" 
              placeholder="请输入职业/专业" 
              maxlength="50"
              show-word-limit
            />
          </el-form-item>
          
          <el-form-item label="宗教信仰" prop="religion">
            <el-select v-model="personalInfo.religion" placeholder="请选择宗教信仰（可选）" class="religion-select">
              <el-option label="无" value="无" />
              <el-option label="佛教" value="佛教" />
              <el-option label="基督教" value="基督教" />
              <el-option label="天主教" value="天主教" />
              <el-option label="伊斯兰教" value="伊斯兰教" />
              <el-option label="道教" value="道教" />
              <el-option label="其他" value="其他" />
            </el-select>
          </el-form-item>
          
          <el-form-item label="掌握语种" class="languages-item">
            <div class="languages-container">
              <el-checkbox-group v-model="personalInfo.languages" class="languages-group">
                <div class="language-grid">
                  <el-checkbox value="英语" class="language-checkbox">英语</el-checkbox>
                  <el-checkbox value="日语" class="language-checkbox">日语</el-checkbox>
                  <el-checkbox value="韩语" class="language-checkbox">韩语</el-checkbox>
                  <el-checkbox value="法语" class="language-checkbox">法语</el-checkbox>
                  <el-checkbox value="德语" class="language-checkbox">德语</el-checkbox>
                  <el-checkbox value="西班牙语" class="language-checkbox">西班牙语</el-checkbox>
                  <el-checkbox value="俄语" class="language-checkbox">俄语</el-checkbox>
                  <el-checkbox value="阿拉伯语" class="language-checkbox">阿拉伯语</el-checkbox>
                </div>
              </el-checkbox-group>
              <div class="language-note">
                <span class="note-icon">💡</span>
                请选择除中文外您掌握的语种，有助于为您提供更好的体验服务
              </div>
            </div>
          </el-form-item>

          <div class="footer-button">
            <el-button 
              type="primary" 
              size="large" 
              @click="savePersonalInfo"
              :loading="saving"
              :disabled="!canSave"
              class="save-btn"
            >
              {{ saving ? '保存中...' : '保存并返回' }}
            </el-button>
          </div>
        </el-form>      
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, computed, onMounted, nextTick } from 'vue'
import { ElMessage } from 'element-plus'
import { getUserStore } from '@/stores/user.js'
import { 
  savePersonalInfo as savePersonalInfoAPI,
  checkPhoneExists,
  getPersonalInfoByToken
} from '@/api/personalInfo.js'

// 定义事件
const emit = defineEmits(['save', 'cancel'])

// 用户store
const userStore = getUserStore()

// 表单引用
const formRef = ref(null)

// 保存状态
const saving = ref(false)



// 手机号检查状态
const phoneCheckStatus = ref('') // '', 'checking', 'available', 'exists'

// 个人信息表单数据
const personalInfo = ref({
  name: '',
  phone: '',
  gender: '',
  age: null,
  education: '',
  occupation: '',
  religion: '无',
  languages: []
})

// 表单验证规则
const formRules = {
  name: [
    { required: true, message: '请输入姓名', trigger: 'blur' },
    { min: 2, max: 20, message: '姓名长度必须在2-20个字符之间', trigger: 'blur' }
  ],
  phone: [
    { required: true, message: '请输入联系电话', trigger: 'blur' },
    { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号码', trigger: 'blur' }
  ],
  gender: [
    { required: true, message: '请选择性别', trigger: 'change' }
  ],
  age: [
    { required: true, message: '请输入年龄', trigger: 'blur' },
    { type: 'number', min: 1, max: 120, message: '年龄必须在1-120之间', trigger: 'blur' }
  ],
  education: [
    { required: true, message: '请选择教育程度', trigger: 'change' }
  ],
  occupation: [
    { required: true, message: '请输入职业', trigger: 'blur' },
    { max: 50, message: '职业长度不能超过50个字符', trigger: 'blur' }
  ]
}

// 计算属性 - 是否可以保存
const canSave = computed(() => {
  return personalInfo.value.name.trim() && 
         personalInfo.value.phone.trim() && 
         personalInfo.value.gender &&
         personalInfo.value.age &&
         personalInfo.value.education &&
         personalInfo.value.occupation.trim() &&
         phoneCheckStatus.value !== 'exists' &&
         !saving.value
})

// 验证手机号格式
const isValidPhone = (phone) => {
  return /^1[3-9]\d{9}$/.test(phone)
}

// 组件挂载时初始化
onMounted(async () => {
  // 打印调试信息
  console.log('🔍 PersonalInfoForm 组件挂载')
  console.log('userStore.userToken:', userStore.userToken)
  console.log('userToken类型:', typeof userStore.userToken)
  console.log('userToken值:', userStore.userToken?.value)
  
  // 尝试获取用户的默认个人信息
  await loadDefaultPersonalInfo()
})

// 加载默认个人信息
const loadDefaultPersonalInfo = async () => {
  // 确保userToken是字符串
  const token = userStore.userToken.value
  if (!token || typeof token !== 'string') {
    console.log('ℹ️ userToken无效或不是字符串:', token, '类型:', typeof token)
    return
  }

  try {
    console.log('🔍 正在加载默认个人信息, userToken:', token)
    const response = await getPersonalInfoByToken(token)
    if (response.code === 200 && response.data) {
      // 填充表单数据
      const data = response.data
      personalInfo.value = {
        name: data.name || '',
        phone: data.phone || '',
        gender: data.gender || '',
        age: data.age || null,
        education: data.education || '',
        occupation: data.occupation || '',
        religion: data.religion || '无',
        languages: data.languages ? JSON.parse(data.languages) : []
      }
      
      console.log('✅ 加载默认个人信息成功')
    }
  } catch (error) {
    console.log('ℹ️ 没有找到默认个人信息，使用空表单')
  }
}



// 处理手机号输入
const handlePhoneInput = (value) => {
  // 只允许输入数字
  personalInfo.value.phone = value.replace(/\D/g, '')
  
  // 重置检查状态
  phoneCheckStatus.value = ''
}

// 处理手机号失焦验证
const handlePhoneBlur = async () => {
  const phone = personalInfo.value.phone.trim()
  if (!phone) return
  
  if (!isValidPhone(phone)) {
    phoneCheckStatus.value = ''
    return
  }

  // 检查手机号是否已存在
  await checkPhoneAvailability(phone)
}

// 检查手机号可用性
const checkPhoneAvailability = async (phone) => {
  phoneCheckStatus.value = 'checking'
  
  try {
    const response = await checkPhoneExists(phone)
    if (response.code === 200) {
      phoneCheckStatus.value = response.data ? 'exists' : 'available'
    } else {
      phoneCheckStatus.value = ''
      ElMessage.error('手机号验证失败')
    }
  } catch (error) {
    phoneCheckStatus.value = ''
    ElMessage.error('手机号验证失败，请稍后重试')
  }
}

// 处理年龄输入
const handleAgeInput = (value) => {
  if (value) {
    const numValue = parseInt(value)
    if (numValue < 1) {
      personalInfo.value.age = 1
    } else if (numValue > 120) {
      personalInfo.value.age = 120
    }
  }
}

// 返回上一页
const goBack = () => {
  emit('cancel')
}

// 保存个人信息
const savePersonalInfo = async () => {
  // 表单验证
  if (!formRef.value) return
  
  try {
    await formRef.value.validate()
  } catch (error) {
    ElMessage.error('请检查表单填写是否正确')
    return
  }

  // 检查手机号状态
  if (phoneCheckStatus.value === 'exists') {
    ElMessage.error('该手机号已被使用，每个手机号只能预约一次')
    return
  }

  // 确保用户Token存在并且是字符串
  const token = userStore.userToken.value
  if (!token || typeof token !== 'string') {
    ElMessage.error('用户身份识别失败，请刷新页面重试')
    console.error('❌ userToken无效:', token, '类型:', typeof token)
    return
  }

  saving.value = true

  try {
    // 构造请求数据
    const requestData = {
      userToken: token,
      name: personalInfo.value.name.trim(),
      phone: personalInfo.value.phone.trim(),
      gender: personalInfo.value.gender,
      age: personalInfo.value.age,
      education: personalInfo.value.education,
      occupation: personalInfo.value.occupation.trim(),
      religion: personalInfo.value.religion || '无',
      languages: JSON.stringify(personalInfo.value.languages),
      isDefault: true
    }

    console.log('💾 保存个人信息:', requestData)

    // 调用API保存
    const response = await savePersonalInfoAPI(requestData)
    
    if (response.code === 200) {
      ElMessage.success('个人信息保存成功！')
      
      // 向父组件发送保存成功事件
      emit('save', {
        ...response.data,
        languages: personalInfo.value.languages // 保持前端格式
      })
    } else {
      ElMessage.error(response.message || '保存失败')
    }
    
  } catch (error) {
    console.error('保存个人信息失败:', error)
    ElMessage.error(error.response?.data?.message || '保存失败，请稍后重试')
  } finally {
    saving.value = false
  }
}
</script>

<style scoped>
@import '../assets/css/booking/personalInfo.css';

.phone-error {
  color: #f56c6c;
  font-size: 12px;
  margin-top: 5px;
}

.el-form-item.is-error .phone-error {
  display: block;
}
</style> 